#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h> //原生线程库的头文件

using namespace std;

const int threadnum = 5;

class Task
{
public:
    Task()
    {   }
    void SetData(int x, int y)
    {
        datax = x;
        datay = y;
    }
    int Excute()
    {
        return datax + datay;
    }
    ~Task()
    {   }
private:
    int datax;
    int datay;
};

class ThreadData : public Task
{
public:
    ThreadData(int x, int y, const string &threadname) :_threadname(threadname)
    {
        _t.SetData(x, y);
    }
    string threadname()
    {
        return _threadname;
    }
    int run()
    {
        return _t.Excute();
    }
private:
    string _threadname;
    Task _t;
};

class Result
{
public:
    Result() {    }
    ~Result() {    }
    void SetResult(int result, const string &threadname)
    {
        _result = result;
        _threadname = threadname;
    }
    void Print()
    {
        cout << _threadname << " : " << _result << endl;
    }
private:
    int _result;
    string _threadname;
};

void* handlerTask(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);  
    string name = td->threadname();
    int result = td->run();

    Result* res = new Result();
    res->SetResult(result, name);
    res->Print();

    delete res;
    delete td;

    sleep(2);
    return (void*)res;
}

int main()
{
    //创建多线程
    vector<pthread_t> threads;
    for (int i = 0; i < threadnum; i++)
    {
        char threadname[64];
        snprintf(threadname, 64, "Thread-%d", i + 1);
        ThreadData *td = new ThreadData(10, i + 1, threadname);

        pthread_t tid;
        pthread_create(&tid, nullptr, handlerTask, td);
        threads.push_back(tid);
    }
    //清理多线程
    void *ret = nullptr;
    for (auto &tid : threads)
    {
        pthread_join(tid, &ret);
    }
    return 0;
}
